package com.ssyc.gsk_master.activity;

import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.github.aakira.expandablelayout.Utils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.ssyc.common.base.BaseActivity;
import com.ssyc.common.base.BaseApplication;
import com.ssyc.common.base.SpKeys;
import com.ssyc.common.http.HttpAdress;
import com.ssyc.common.http.HttpUtils;
import com.ssyc.common.manager.AccountUtils;
import com.ssyc.common.manager.PopUpManager;
import com.ssyc.common.manager.SrfManager;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.utils.SPUtil;
import com.ssyc.common.utils.SnackbarUtil;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.common.view.MyGridView;
import com.ssyc.gsk_master.R;
import com.ssyc.gsk_master.adapter.ClassGvAdapter;
import com.ssyc.gsk_master.adapter.MasterFansiRvAdapter;
import com.ssyc.gsk_master.bean.ClassInfo;
import com.ssyc.gsk_master.bean.UnitBean;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 教学与反思
 * Created by Administrator on 2018/8/3 0003.
 */

public class MasterFansiActivity extends BaseActivity implements View.OnClickListener {
    //返回键
    private ImageView ivBack;

    //加载框
    private RelativeLayout rlLoading;

    //列表数据
    private RecyclerView rv;

    //下拉刷新控件
    private SmartRefreshLayout srf;

    //列表适配器
    private MasterFansiRvAdapter adapter;

    //适配器的数据集合
    private List<UnitBean.DataBean> oldDatas;

    //选班
    private TextView tv_choice_class;

    //Handler对象
    private Handler handler = new Handler();

    //所有班级的列表
    private List<ClassInfo.ListBean> classInfos;

    //标题栏的布局
    private LinearLayout llTitle;

    //展示班级列表的适配器
    private ClassGvAdapter classGvAdapter;

    //记录弹出展示班级列表PopUpWindow的选中位置的值,默认第一个被选中
    private int popSelectedPos = 0;

    //是否获取班级列表数据完成的标识,没完成之前点击选择班级的弹框提示正在加载,不允许点击
    private boolean isLoadClassCompleted;

    //老师账号
    private String acc;

    @Override
    protected boolean isNeedShowTitle() {
        return false;
    }

    @Override
    protected String setTitleText() {
        return null;
    }

    @Override
    protected int getContentLayout() {
        return R.layout.master_activity_fansi;
    }

    @Override
    protected void init() {

        showContent();

        //获取老师账号和角色(从校长端跳过来的时需要)
        InitIntent();

        //初始化视图
        initView();

        //初始化下拉刷新控件
        initSrf();

        //请求服务器数据获取班级列表
        httpClass();
    }

    /**
     * 接收数据
     */
    private void InitIntent() {

        acc = getIntent().getStringExtra("teacheraccount");

        if (TextUtils.isEmpty(acc)) {
            acc = AccountUtils.getAccount(this);
        }
    }

    /**
     * 获取班级列表的数据
     */
    private void httpClass() {
        Map<String, String> map = new HashMap<>();
        map.put("type", "5");
        map.put("c", acc);
        map.put("user_type", SPUtil.getString(this, SpKeys.USERTYPE));
        map.put("platform", "8");
        HttpUtils.post(HttpAdress.GETCLASS, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (null != rlLoading && rlLoading.getVisibility() != View.GONE) {
                    rlLoading.setVisibility(View.GONE);
                }
                UiUtils.Toast(BaseApplication.ERROR, false);
            }

            @Override
            public void onResponse(String response, int id) {
                ClassInfo info = null;
                try {
                    info = GsonUtil.jsonToBean(response, ClassInfo.class);
                } catch (Exception e) {
                    Log.i("test", "数据解析异常");
                }

                if (null != info) {
                    if ("1".equals(info.getStatus())) {
                        //返回成功
                        classInfos = info.getList();
                        if (null != classInfos && classInfos.size() != 0) {
                            //加载完班级列表数据后并且设置好列表展示数据后标题栏选择班级弹框可以进行点击了
                            isLoadClassCompleted = true;

                            //默认加载第一个班级的数据
                            httpLesson(0);
                        } else {
                            if (null != rlLoading && rlLoading.getVisibility() != View.GONE) {
                                rlLoading.setVisibility(View.GONE);
                            }
                            UiUtils.Toast("没有班级数据", false);
                        }

                    } else {
                        //返回错误
                        UiUtils.Toast("服务器返回异常,状态码是:" + info.getStatus(), false);
                        Log.i("test", "服务器返回异常,状态码是:" + info.getStatus());
                    }

                } else {
                    Log.i("test", "服务器返回数据为空");
                }

            }
        });
    }

    /**
     * 弹窗
     */
    private void onChoiceClass() {

        if (null == classInfos || classInfos.size() == 0) {
            //证明没有班级列表数据,不做任何操作
            return;
        } else {
            PopUpManager.showPop(this, R.layout.master_pop_class, 0.3f, llTitle, new PopUpManager.onGetViewListener() {
                @Override
                public void getChildView(View view, int layoutResId) {
                    //展示班级列表的GridView
                    MyGridView gv = view.findViewById(R.id.gv);


                    //第一步:设置默认的选中状态的班级位置
                    syncClassGvState();

                    //第二步:设置列表数据
                    classGvAdapter = new ClassGvAdapter(MasterFansiActivity.this,
                            classInfos, R.layout.master_gv_class);
                    gv.setAdapter(classGvAdapter);

                    //第三步:设置点击事件
                    gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {
                            //记录选中的位置
                            popSelectedPos = pos;

                            //同步GridView的状态,设置列表的选中状态
                            syncClassGvState();

                            //通知适配器刷新
                            classGvAdapter.notifyDataSetChanged();

                            //根据当前选中的班级去请求班级小组的数据
                            httpLesson(pos);

                            //延迟关闭弹框
                            handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    PopUpManager.dismiss();
                                }
                            }, 100);

                        }
                    });
                }
            });
        }
    }


    /**
     * 同步班级列表GridView的选中和没选中的状态
     */
    private void syncClassGvState() {
        for (int i = 0; i < classInfos.size(); i++) {
            if (popSelectedPos == i) {
                classInfos.get(i).setSelected(true);
            } else {
                classInfos.get(i).setSelected(false);
            }
        }
    }

    /**
     * 请求服务器数据
     */
    private void httpLesson(int pos) {

        Map<String, String> map = new HashMap<>();

        map.put("type", "1");

        map.put("acc", AccountUtils.getAccount(this));

        map.put("role", AccountUtils.getRole(this));

        map.put("platform", "8");

        HttpUtils.post(HttpAdress.GETLESSONList, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                showLoadingView(rlLoading, true);
            }

            @Override
            public void onResponse(String response, int id) {
                showLoadingView(rlLoading, false);
                if (!TextUtils.isEmpty(response)) {
                    UnitBean info = null;
                    try {
                        info = GsonUtil.jsonToBean(response, UnitBean.class);
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.i("test", "数据解析异常");
                    }
                    if (info != null) {
                        if ("200".equals(info.getState())) {
                            //返回成功
                            oldDatas = info.getData();
                            if (null != oldDatas && oldDatas.size() != 0) {

                                //添加折叠动画效果
                                for (int i = 0; i < oldDatas.size(); i++) {
                                    oldDatas.get(i).setInterpolator(Utils.createInterpolator(Utils.LINEAR_OUT_SLOW_IN_INTERPOLATOR));
                                }
                                //设置适配器
                                initLv();
                            } else {
                                Log.i("test", "服务器返回数据为空");
                            }
                        } else {
                            Log.i("test", "返回错误码是:" + info.getState());
                        }
                    }
                }
            }
        });
    }


    /**
     * 初始化页面控件
     */
    public void initView() {
        ivBack = findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);
        rv = findViewById(R.id.rv);
        srf = findViewById(R.id.srf);
        rlLoading = findViewById(R.id.rl_loading_view);
        rlLoading.setVisibility(View.VISIBLE);

        tv_choice_class = findViewById(R.id.tv_choice_class);
        tv_choice_class.setOnClickListener(this);
        //标题栏
        llTitle = findViewById(R.id.ll_title);
    }

    /**
     * 初始化下拉刷新控件
     */
    private void initSrf() {
        SrfManager.setSmartByPullListener(srf, null);
    }


    /**
     * 设置列表的方法
     */
    private void initLv() {
        rv.setHasFixedSize(true);
        rv.setLayoutManager(new LinearLayoutManager(this));
        adapter = new MasterFansiRvAdapter(this, R.layout.master_rv_new_concept, oldDatas);
        rv.setAdapter(adapter);
    }


    /**
     * 页面控件的点击事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_back) {
            //返回
            finish();
        } else if (id == R.id.tv_choice_class) {
            //选择班级
            if (isLoadClassCompleted) {
                //弹出选择班级的PopUpWindow
                onChoiceClass();
            } else {
                //没加载完成
                SnackbarUtil.ShortSnackbar(llBaseMain, "正在加载,不能选择班级", 0);
            }
        }
    }
}
